<!DOCTYPE html>
<html>
<head><meta name="generator" content="Hexo 3.9.0">
    <meta charset="utf-8">
    
    <title>TypeScript 基础类型 | Shaw Blog</title>
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    
        <meta name="keywords" content="ts,typescript,TypeScript,前端博客,JavaScript,html5,css3,ES6,NodeJs,shaw blog">
        
    <meta content="yes" name="apple-mobile-web-app-capable">
    <meta name="description" content="TypeScript 支持与 JavaScript 几乎相同的数据类型，此外还提供了实用的枚举类型方便我们使用。">
<meta name="keywords" content="ts,typescript,TypeScript">
<meta property="og:type" content="article">
<meta property="og:title" content="TypeScript 基础类型">
<meta property="og:url" content="https://ipvb.gitee.io/blog/2019/01/20/TypeScript-基础类型/index.html">
<meta property="og:site_name" content="Shaw Blog">
<meta property="og:description" content="TypeScript 支持与 JavaScript 几乎相同的数据类型，此外还提供了实用的枚举类型方便我们使用。">
<meta property="og:locale" content="default">
<meta property="og:image" content="http://image.nicebp.com/blog/banner/TB1xJN9QXXXXXbXXpXXXXXXXXXX-900-500.jpg?imageView2/1/w/690/h/295/q/75">
<meta property="og:updated_time" content="2021-01-20T07:54:09.675Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="TypeScript 基础类型">
<meta name="twitter:description" content="TypeScript 支持与 JavaScript 几乎相同的数据类型，此外还提供了实用的枚举类型方便我们使用。">
<meta name="twitter:image" content="http://image.nicebp.com/blog/banner/TB1xJN9QXXXXXbXXpXXXXXXXXXX-900-500.jpg?imageView2/1/w/690/h/295/q/75">
    

    
        <link rel="alternate" href="/" title="Shaw Blog" type="application/atom+xml">
    

    

    <link rel="stylesheet" href="/blog/libs/font-awesome/css/font-awesome.min.css">
    <link rel="stylesheet" href="/blog/libs/open-sans/styles.css">
    <link rel="stylesheet" href="/blog/libs/source-code-pro/styles.css">

    <!-- <link rel="stylesheet" href="/blog/css/style.css"> -->
    <link rel="stylesheet" href="/blog/css/style_dark.css">

    <script src="/blog/libs/jquery/2.1.3/jquery.min.js"></script>
    
    
        <link rel="stylesheet" href="/blog/libs/lightgallery/css/lightgallery.min.css">
    
    
        <link rel="stylesheet" href="/blog/libs/justified-gallery/justifiedGallery.min.css">
    
    
    
    


</head>
</html>
<body>
    <div id="container">
        <header id="header">
    <div id="header-main" class="header-inner">
        <div class="outer">
            <a href="/blog/" id="logo">
                
                <span class="site-title">Shaw Blog</span>
            </a>
            <nav id="main-nav">
                
                    <a class="main-nav-link" href="/blog/.">Home</a>
                
                    <a class="main-nav-link" href="/blog/archives">Archives</a>
                
                    <a class="main-nav-link" href="/blog/categories">Categories</a>
                
                    <a class="main-nav-link" href="/blog/tags">Tags</a>
                
                    <a class="main-nav-link" href="/blog/about">About</a>
                
            </nav>
            
                
                <nav id="sub-nav">
                    <div class="profile" id="profile-nav">
                        <a id="profile-anchor" href="javascript:;">
                            <img class="avatar" src="/blog/css/images/avatar.png" />
                            <i class="fa fa-caret-down"></i>
                        </a>
                    </div>
                </nav>
            
            <div id="search-form-wrap">

    <form class="search-form">
        <input type="text" class="ins-search-input search-form-input" placeholder="Search" />
        <button type="submit" class="search-form-submit"></button>
    </form>
    <div class="ins-search">
    <div class="ins-search-mask"></div>
    <div class="ins-search-container">
        <div class="ins-input-wrapper">
            <input type="text" class="ins-search-input" placeholder="Type something..." />
            <span class="ins-close ins-selectable"><i class="fa fa-times-circle"></i></span>
        </div>
        <div class="ins-section-wrapper">
            <div class="ins-section-container"></div>
        </div>
    </div>
</div>
<script>
(function (window) {
    var INSIGHT_CONFIG = {
        TRANSLATION: {
            POSTS: 'Posts',
            PAGES: 'Pages',
            CATEGORIES: 'Categories',
            TAGS: 'Tags',
            UNTITLED: '(Untitled)',
        },
        ROOT_URL: '/blog/',
        CONTENT_URL: '/blog/content.json',
    };
    window.INSIGHT_CONFIG = INSIGHT_CONFIG;
})(window);
</script>
<script src="/blog/js/insight.js"></script>

</div>
        </div>
    </div>
    <div id="main-nav-mobile" class="header-sub header-inner">
        <table class="menu outer">
            <tr>
                
                    <td><a class="main-nav-link" href="/blog/.">Home</a></td>
                
                    <td><a class="main-nav-link" href="/blog/archives">Archives</a></td>
                
                    <td><a class="main-nav-link" href="/blog/categories">Categories</a></td>
                
                    <td><a class="main-nav-link" href="/blog/tags">Tags</a></td>
                
                    <td><a class="main-nav-link" href="/blog/about">About</a></td>
                
                <td>
                    
    <div class="search-form">
        <input type="text" class="ins-search-input search-form-input" placeholder="Search" />
    </div>

                </td>
            </tr>
        </table>
    </div>
</header>

        <div class="outer">
            
                

<aside id="profile">
    <div class="inner profile-inner">
        <div class="base-info profile-block">
            <img id="avatar" src="/blog/css/images/avatar.png" />
            <h2 id="name">ShawYo</h2>
            <h3 id="title">Web Developer &amp; Designer</h3>
            <span id="location"><i class="fa fa-map-marker"></i>HangZhou, China</span>
            <a id="follow" target="_blank" href="https://github.com/shawyo/">FOLLOW</a>
        </div>
        <div class="article-info profile-block">
            <div class="article-info-block">
                16
                <span>posts</span>
            </div>
            <div class="article-info-block">
                6
                <span>tags</span>
            </div>
        </div>
        <!-- 
        <div class="profile-block social-links">
            <table>
                <tr>
                    
                    
                    <td>
                        <a href="https://github.com/shawyo/" target="_blank" title="github" class=tooltip>
                            <i class="fa fa-github"></i>
                        </a>
                    </td>
                    
                    <td>
                        <a href="/blog/" target="_blank" title="twitter" class=tooltip>
                            <i class="fa fa-twitter"></i>
                        </a>
                    </td>
                    
                    <td>
                        <a href="/blog/" target="_blank" title="facebook" class=tooltip>
                            <i class="fa fa-facebook"></i>
                        </a>
                    </td>
                    
                    <td>
                        <a href="/blog/" target="_blank" title="dribbble" class=tooltip>
                            <i class="fa fa-dribbble"></i>
                        </a>
                    </td>
                    
                    <td>
                        <a href="/blog/" target="_blank" title="rss" class=tooltip>
                            <i class="fa fa-rss"></i>
                        </a>
                    </td>
                    
                </tr>
            </table>
        </div>
         -->
    </div>
</aside>

            
            <section id="main"><article id="post-TypeScript-基础类型" class="article article-type-post" itemscope itemprop="blogPost">
    <div class="article-inner">
        
            
	
		<img src="http://image.nicebp.com/blog/banner/TB1xJN9QXXXXXbXXpXXXXXXXXXX-900-500.jpg?imageView2/1/w/690/h/295/q/75" class="article-banner" />
	



        
        
            <header class="article-header">
                
    
        <h1 class="article-title" itemprop="name">
            TypeScript 基础类型
        </h1>
    

                
                    <div class="article-meta">
                        
    <div class="article-date">
        <i class="fa fa-calendar"></i>
        <a href="/blog/2019/01/20/TypeScript-基础类型/">
            <time datetime="2019-01-20T07:01:55.000Z" itemprop="datePublished">2019-01-20</time>
        </a>
    </div>


                        
    <div class="article-category">
    	<i class="fa fa-folder"></i>
        <a class="article-category-link" href="/blog/categories/TypeScript/">TypeScript</a>
    </div>

                        
    <div class="article-tag">
        <i class="fa fa-tag"></i>
        <a class="tag-link" href="/blog/tags/TypeScript/">TypeScript</a>
    </div>

                    </div>
                
            </header>
        
        
        <div class="article-entry" itemprop="articleBody">
        
            
            <p>TypeScript 支持与 JavaScript 几乎相同的数据类型，此外还提供了实用的枚举类型方便我们使用。</p>
<a id="more"></a>
<h2 id="布尔值-boolean"><a href="#布尔值-boolean" class="headerlink" title="布尔值 boolean"></a>布尔值 <code>boolean</code></h2><hr>
<p>最基本的数据类型就是简单的 true/false 值，在 JavaScript 和 TypeScript 里叫做 boolean（其它语言中也一样）。</p>
<figure class="highlight ts"><table><tr><td class="code"><pre><span class="line"><span class="keyword">let</span> isDone: <span class="built_in">boolean</span> = <span class="literal">false</span>;</span><br><span class="line">isDone = <span class="literal">true</span>;</span><br><span class="line"><span class="comment">// isDone = 2 // error</span></span><br></pre></td></tr></table></figure>
<h2 id="数字-number"><a href="#数字-number" class="headerlink" title="数字 number"></a>数字 <code>number</code></h2><hr>
<p>和 JavaScript 一样，TypeScript 里的所有数字都是浮点数。 这些浮点数的类型是 number。 除了支持十进制和十六进制字面量，TypeScript 还支持 ECMAScript 2015 中引入的二进制和八进制字面量。</p>
<figure class="highlight ts"><table><tr><td class="code"><pre><span class="line"><span class="keyword">let</span> a1: <span class="built_in">number</span> = <span class="number">10</span>; <span class="comment">// 十进制</span></span><br><span class="line"><span class="keyword">let</span> a2: <span class="built_in">number</span> = <span class="number">0b1010</span>; <span class="comment">// 二进制</span></span><br><span class="line"><span class="keyword">let</span> a3: <span class="built_in">number</span> = <span class="number">0o12</span>; <span class="comment">// 八进制</span></span><br><span class="line"><span class="keyword">let</span> a4: <span class="built_in">number</span> = <span class="number">0xa</span>; <span class="comment">// 十六进制</span></span><br></pre></td></tr></table></figure>
<h2 id="字符串-string"><a href="#字符串-string" class="headerlink" title="字符串 string"></a>字符串 <code>string</code></h2><hr>
<p>JavaScript 程序的另一项基本操作是处理网页或服务器端的文本数据。 像其它语言里一样，我们使用 string 表示文本数据类型。 和 JavaScript 一样，可以使用双引号（”）或单引号（’）表示字符串。</p>
<figure class="highlight ts"><table><tr><td class="code"><pre><span class="line"><span class="keyword">let</span> name: <span class="built_in">string</span> = <span class="string">"Tom"</span>;</span><br><span class="line">name = <span class="string">"jreey"</span>;</span><br><span class="line"><span class="comment">// name = 10 //error</span></span><br></pre></td></tr></table></figure>
<h2 id="undefined-和-null"><a href="#undefined-和-null" class="headerlink" title="undefined 和 null"></a><code>undefined</code> 和 <code>null</code></h2><hr>
<p>TypeScript 里，undefined 和 null 两者各自有自己的类型分别叫做 undefined 和 null。 它们的本身的类型用处不是很大<br>默认情况下 null 和 undefined 是所有类型的子类型。 就是说你可以把 null 和 undefined 赋值给 number 类型的变量。</p>
<figure class="highlight ts"><table><tr><td class="code"><pre><span class="line"><span class="keyword">let</span> u: <span class="literal">undefined</span> = <span class="literal">undefined</span>;</span><br><span class="line"><span class="keyword">let</span> n: <span class="literal">null</span> = <span class="literal">null</span>;</span><br></pre></td></tr></table></figure>
<h2 id="数组-array"><a href="#数组-array" class="headerlink" title="数组 array"></a>数组 <code>array</code></h2><hr>
<p>TypeScript 像 JavaScript 一样可以操作数组元素。 有两种方式可以定义数组。 第一种，可以在元素类型后面接上[]，表示由此类型元素组成的一个数组：</p>
<figure class="highlight ts"><table><tr><td class="code"><pre><span class="line"><span class="keyword">let</span> arr1: <span class="built_in">number</span>[] = [<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>];</span><br></pre></td></tr></table></figure>
<p>第二种方式是使用数组泛型，<code>Array&lt;元素类型&gt;</code>：</p>
<figure class="highlight ts"><table><tr><td class="code"><pre><span class="line"><span class="keyword">let</span> arr2: <span class="built_in">Array</span>[<span class="built_in">number</span>] = [<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>];</span><br><span class="line"><span class="keyword">let</span> arr3: <span class="built_in">Array</span>[<span class="built_in">string</span>] = [<span class="string">"1"</span>, <span class="string">"2"</span>, <span class="string">"3"</span>];</span><br></pre></td></tr></table></figure>
<h2 id="元组-Tuple"><a href="#元组-Tuple" class="headerlink" title="元组 Tuple"></a>元组 <code>Tuple</code></h2><hr>
<p>元组类型允许表示一个已知元素数量和类型的数组，各元素的类型不必相同。 比如，你可以定义一对值分别为 string 和 number 类型的元组。</p>
<figure class="highlight ts"><table><tr><td class="code"><pre><span class="line"><span class="keyword">let</span> t = [<span class="built_in">string</span>, <span class="built_in">number</span>];</span><br><span class="line">t = [<span class="string">"tom"</span>, <span class="number">10</span>]; <span class="comment">// success</span></span><br><span class="line">t = [<span class="number">10</span>, <span class="string">"tom"</span>]; <span class="comment">// error</span></span><br></pre></td></tr></table></figure>
<p>当访问一个已知索引的元素，会得到正确的类型：</p>
<figure class="highlight ts"><table><tr><td class="code"><pre><span class="line"><span class="built_in">console</span>.log(t[<span class="number">0</span>].substring(<span class="number">1</span>)); <span class="comment">// success</span></span><br><span class="line"><span class="built_in">console</span>.log(t[<span class="number">1</span>].substring(<span class="number">1</span>)); <span class="comment">// error, 'number' 不存在 'substring' 方法</span></span><br></pre></td></tr></table></figure>
<h2 id="枚举-enum"><a href="#枚举-enum" class="headerlink" title="枚举 enum"></a>枚举 <code>enum</code></h2><hr>
<p>enum 类型是对 JavaScript 标准数据类型的一个补充。 使用枚举类型可以为一组数值赋予友好的名字</p>
<figure class="highlight ts"><table><tr><td class="code"><pre><span class="line"><span class="keyword">enum</span> Color &#123;</span><br><span class="line">  red,</span><br><span class="line">  green,</span><br><span class="line">  blue,</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 枚举数值默认从0开始依次递增</span></span><br><span class="line"><span class="comment">// 根据特定的名称得到对应的枚举数值</span></span><br><span class="line"><span class="keyword">let</span> myColor: Color = Color.red; <span class="comment">// 0</span></span><br><span class="line"><span class="built_in">console</span>.log(myColor, Color.red, Color.blue);</span><br></pre></td></tr></table></figure>
<p>默认情况下，从 0 开始为元素编号。 你也可以手动的指定成员的数值。 例如，我们将上面的例子改成从 1 开始编号：</p>
<figure class="highlight ts"><table><tr><td class="code"><pre><span class="line"><span class="keyword">enum</span> Color &#123;</span><br><span class="line">  red = <span class="number">1</span>,</span><br><span class="line">  green,</span><br><span class="line">  blue,</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">let</span> c: Color = Color.green;</span><br></pre></td></tr></table></figure>
<p>或者，全部都采用手动赋值：</p>
<figure class="highlight ts"><table><tr><td class="code"><pre><span class="line"><span class="keyword">enum</span> Color &#123;</span><br><span class="line">  red = <span class="number">1</span>,</span><br><span class="line">  green = <span class="number">2</span>,</span><br><span class="line">  blue = <span class="number">4</span>,</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">let</span> c: Color = Color.green;</span><br></pre></td></tr></table></figure>
<p>枚举类型提供的一个便利是你可以由枚举的值得到它的名字。 例如，我们知道数值为 2，但是不确定它映射到 Color 里的哪个名字，我们可以查找相应的名字：</p>
<figure class="highlight ts"><table><tr><td class="code"><pre><span class="line"><span class="keyword">enum</span> Color &#123;</span><br><span class="line">  red = <span class="number">1</span>,</span><br><span class="line">  green,</span><br><span class="line">  blue,</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">let</span> colorName: <span class="built_in">string</span> = Color[<span class="number">2</span>];</span><br><span class="line"></span><br><span class="line"><span class="built_in">console</span>.log(colorName); <span class="comment">// "green"</span></span><br></pre></td></tr></table></figure>
<h2 id="any"><a href="#any" class="headerlink" title="any"></a><code>any</code></h2><hr>
<p>有时候，我们会想要为那些在编程阶段还不清楚类型的变量指定一个类型。 这些值可能来自于动态的内容，比如来自用户输入或第三方代码库。 这种情况下，我们不希望类型检查器对这些值进行检查而是直接让它们通过编译阶段的检查。 那么我们可以使用 any 类型来标记这些变量：</p>
<figure class="highlight ts"><table><tr><td class="code"><pre><span class="line"><span class="keyword">let</span> txt: <span class="built_in">any</span> = <span class="number">12</span>;</span><br><span class="line">txt = <span class="string">"tom"</span>;</span><br><span class="line">txt = <span class="literal">true</span>; <span class="comment">// 也可以是个 boolean</span></span><br></pre></td></tr></table></figure>
<p>在对现有代码进行改写的时候，any 类型是十分有用的，它允许你在编译时可选择地包含或移除类型检查。并且当你只知道一部分数据的类型时，any 类型也是有用的。 比如，你有一个数组，它包含了不同的类型的数据：</p>
<figure class="highlight ts"><table><tr><td class="code"><pre><span class="line"><span class="keyword">let</span> list: <span class="built_in">any</span>[] = [<span class="number">1</span>, <span class="literal">true</span>, <span class="string">"tom"</span>];</span><br><span class="line">list[<span class="number">1</span>] = <span class="number">12</span>;</span><br></pre></td></tr></table></figure>
<h2 id="void"><a href="#void" class="headerlink" title="void"></a><code>void</code></h2><hr>
<p>某种程度上来说，void 类型像是与 any 类型相反，它表示没有任何类型。 当一个函数没有返回值时，你通常会见到其返回值类型是 void</p>
<figure class="highlight ts"><table><tr><td class="code"><pre><span class="line"><span class="comment">/* 表示没有任何类型, 一般用来说明函数的返回值不能是undefined和null之外的值 */</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">fn</span>(<span class="params"></span>): <span class="title">void</span> </span>&#123;</span><br><span class="line">  <span class="built_in">console</span>.log(<span class="string">"fn()"</span>);</span><br><span class="line">  <span class="comment">// return undefined</span></span><br><span class="line">  <span class="comment">// return null</span></span><br><span class="line">  <span class="comment">// return 1 // error</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>声明一个 void 类型的变量没有什么大用，因为你只能为它赋予 undefined 和 null</p>
<figure class="highlight ts"><table><tr><td class="code"><pre><span class="line"><span class="keyword">let</span> unusable: <span class="built_in">void</span> = <span class="literal">undefined</span>;</span><br></pre></td></tr></table></figure>
<h2 id="object"><a href="#object" class="headerlink" title="object"></a><code>object</code></h2><p>object 表示非原始类型，也就是除 number，string，boolean 之外的类型。<br>使用 object 类型，就可以更好的表示像 Object.create 这样的 API。例如：</p>
<figure class="highlight ts"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">fn2</span>(<span class="params">obj: object</span>): <span class="title">object</span> </span>&#123;</span><br><span class="line">  <span class="built_in">console</span>.log(<span class="string">"fn2()"</span>, obj);</span><br><span class="line">  <span class="keyword">return</span> &#123;&#125;;</span><br><span class="line">  <span class="comment">// return undefined</span></span><br><span class="line">  <span class="comment">// return null</span></span><br><span class="line">&#125;</span><br><span class="line"><span class="built_in">console</span>.log(fn2(<span class="keyword">new</span> <span class="built_in">String</span>(<span class="string">"abc"</span>)));</span><br><span class="line"><span class="comment">// console.log(fn2('abc') // error</span></span><br><span class="line"><span class="built_in">console</span>.log(fn2(<span class="built_in">String</span>));</span><br></pre></td></tr></table></figure>
<h2 id="联合类型-Union-Types"><a href="#联合类型-Union-Types" class="headerlink" title="联合类型 Union Types"></a>联合类型 <code>Union Types</code></h2><p>联合类型（Union Types）表示取值可以为多种类型中的一种<br>需求 1: 定义一个一个函数得到一个数字或字符串值的字符串形式值</p>
<figure class="highlight ts"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">toString2</span>(<span class="params">x: <span class="built_in">number</span> | <span class="built_in">string</span></span>): <span class="title">string</span> </span>&#123;</span><br><span class="line">  <span class="keyword">return</span> x.toString();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>需求 2: 定义一个一个函数得到一个数字或字符串值的长度</p>
<figure class="highlight ts"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">getLength</span>(<span class="params">x: <span class="built_in">number</span> | <span class="built_in">string</span></span>) </span>&#123;</span><br><span class="line">  <span class="comment">// return x.length // error</span></span><br><span class="line"></span><br><span class="line">  <span class="keyword">if</span> (x.length) &#123;</span><br><span class="line">    <span class="comment">// error</span></span><br><span class="line">    <span class="keyword">return</span> x.length;</span><br><span class="line">  &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">    <span class="keyword">return</span> x.toString().length;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2 id="类型断言"><a href="#类型断言" class="headerlink" title="类型断言"></a>类型断言</h2><hr>
<p>通过类型断言这种方式可以告诉编译器，“相信我，我知道自己在干什么”。 类型断言好比其它语言里的类型转换，但是不进行特殊的数据检查和解构。 它没有运行时的影响，只是在编译阶段起作用。 TypeScript 会假设你，程序员，已经进行了必须的检查。</p>
<p>类型断言有两种形式。 其一是“尖括号”语法, 另一个为 <code>as</code> 语法</p>
<figure class="highlight ts"><table><tr><td class="code"><pre><span class="line"><span class="comment">/* </span></span><br><span class="line"><span class="comment">类型断言(Type Assertion): 可以用来手动指定一个值的类型</span></span><br><span class="line"><span class="comment">语法:</span></span><br><span class="line"><span class="comment">    方式一: &lt;类型&gt;值</span></span><br><span class="line"><span class="comment">    方式二: 值 as 类型  tsx中只能用这种方式</span></span><br><span class="line"><span class="comment">*/</span></span><br><span class="line"></span><br><span class="line"><span class="comment">/* 需求: 定义一个函数得到一个字符串或者数值数据的长度 */</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">getLength</span>(<span class="params">x: <span class="built_in">number</span> | <span class="built_in">string</span></span>) </span>&#123;</span><br><span class="line">  <span class="keyword">if</span> ((&lt;<span class="built_in">string</span>&gt;x).length) &#123;</span><br><span class="line">    <span class="keyword">return</span> (x <span class="keyword">as</span> <span class="built_in">string</span>).length;</span><br><span class="line">  &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">    <span class="keyword">return</span> x.toString().length;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="built_in">console</span>.log(getLength(<span class="string">"abcd"</span>), getLength(<span class="number">1234</span>));</span><br></pre></td></tr></table></figure>
<h2 id="类型推断"><a href="#类型推断" class="headerlink" title="类型推断"></a>类型推断</h2><hr>
<p>类型推断: TS 会在没有明确的指定类型的时候推测出一个类型<br>有下面 2 种情况: 1. 定义变量时赋值了, 推断为对应的类型. 2. 定义变量时没有赋值, 推断为 any 类型</p>
<figure class="highlight ts"><table><tr><td class="code"><pre><span class="line"><span class="comment">/* 定义变量时赋值了, 推断为对应的类型 */</span></span><br><span class="line"><span class="keyword">let</span> b9 = <span class="number">123</span>; <span class="comment">// number</span></span><br><span class="line"><span class="comment">// b9 = 'abc' // error</span></span><br><span class="line"></span><br><span class="line"><span class="comment">/* 定义变量时没有赋值, 推断为any类型 */</span></span><br><span class="line"><span class="keyword">let</span> b10; <span class="comment">// any类型</span></span><br><span class="line">b10 = <span class="number">123</span>;</span><br><span class="line">b10 = <span class="string">"abc"</span>;</span><br></pre></td></tr></table></figure>

        
        </div>
        <footer class="article-footer">
            <div class="share-container">


    <div class="bdsharebuttonbox">
    <a href="#" class="bds_more" data-cmd="more">分享到：</a>
    <a href="#" class="bds_qzone" data-cmd="qzone" title="分享到QQ空间">QQ空间</a>
    <a href="#" class="bds_tsina" data-cmd="tsina" title="分享到新浪微博">新浪微博</a>
    <a href="#" class="bds_tqq" data-cmd="tqq" title="分享到腾讯微博">腾讯微博</a>
    <a href="#" class="bds_renren" data-cmd="renren" title="分享到人人网">人人网</a>
    <a href="#" class="bds_weixin" data-cmd="weixin" title="分享到微信">微信</a>
</div>
<script>
window._bd_share_config={"common":{"bdSnsKey":{},"bdText":"","bdMini":"2","bdMiniList":false,"bdPic":"","bdStyle":"0","bdSize":"16"},"share":{"bdSize":16}};with(document)0[(getElementsByTagName('head')[0]||body).appendChild(createElement('script')).src='http://bdimg.share.baidu.com/static/api/js/share.js?v=89860593.js?cdnversion='+~(-new Date()/36e5)];
</script>
<style>
    .bdshare_popup_box {
        border-radius: 4px;
        border: #e1e1e1 solid 1px;
    }
    .bdshare-button-style0-16 a,
    .bdshare-button-style0-16 .bds_more {
        padding-left: 20px;
        margin: 6px 10px 6px 0;
    }
    .bdshare_dialog_list a,
    .bdshare_popup_list a,
    .bdshare_popup_bottom a {
        font-family: 'Microsoft Yahei';
    }
    .bdshare_popup_top {
        display: none;
    }
    .bdshare_popup_bottom {
        height: auto;
        padding: 5px;
    }
</style>


</div>

            
    

        </footer>
    </div>
    
        
<nav id="article-nav">
    
        <a href="/blog/2019/01/21/TypeScript-接口/" id="article-nav-newer" class="article-nav-link-wrap">
            <strong class="article-nav-caption">Newer</strong>
            <div class="article-nav-title">
                
                    TypeScript 接口
                
            </div>
        </a>
    
    
        <a href="/blog/2018/02/22/ESLint-VSCode自动化配置/" id="article-nav-older" class="article-nav-link-wrap">
            <strong class="article-nav-caption">Older</strong>
            <div class="article-nav-title">ESLint&amp;VSCode自动化配置</div>
        </a>
    
</nav>


    
</article>


    
    
        <section id="comments">
    <div id="valine-thread"></div>
</section>
    

</section>
            
                
<aside id="sidebar">
   
        
    <div class="widget-wrap">
        <h3 class="widget-title">recent</h3>
        <div class="widget">
            <ul id="recent-post" class="">
                
                    <li>
                        
                        <div class="item-thumbnail">
                            <a href="/blog/2021/01/23/TypeScript-函数/" class="thumbnail">
    
    
        <span style="background-image:url(https://www.tslang.cn/assets/images/foreground_bluprint.svg)" alt="TypeScript 函数" class="thumbnail-image"></span>
    
</a>

                        </div>
                        
                        <div class="item-inner">
                            <p class="item-category"><a class="article-category-link" href="/blog/categories/TypeScript/">TypeScript</a></p>
                            <p class="item-title"><a href="/blog/2021/01/23/TypeScript-函数/" class="title">TypeScript 函数</a></p>
                            <p class="item-date"><time datetime="2021-01-23T08:14:16.000Z" itemprop="datePublished">2021-01-23</time></p>
                        </div>
                    </li>
                
                    <li>
                        
                        <div class="item-thumbnail">
                            <a href="/blog/2019/01/22/TypeScript-类/" class="thumbnail">
    
    
        <span style="background-image:url(https://www.tslang.cn/assets/images/foreground_bluprint.svg)" alt="TypeScript 类" class="thumbnail-image"></span>
    
</a>

                        </div>
                        
                        <div class="item-inner">
                            <p class="item-category"><a class="article-category-link" href="/blog/categories/TypeScript/">TypeScript</a></p>
                            <p class="item-title"><a href="/blog/2019/01/22/TypeScript-类/" class="title">TypeScript 类</a></p>
                            <p class="item-date"><time datetime="2019-01-22T02:27:59.000Z" itemprop="datePublished">2019-01-22</time></p>
                        </div>
                    </li>
                
                    <li>
                        
                        <div class="item-thumbnail">
                            <a href="/blog/2019/01/21/TypeScript-接口/" class="thumbnail">
    
    
        <span style="background-image:url(https://www.tslang.cn/assets/images/foreground_bluprint.svg)" alt="TypeScript 接口" class="thumbnail-image"></span>
    
</a>

                        </div>
                        
                        <div class="item-inner">
                            <p class="item-category"><a class="article-category-link" href="/blog/categories/TypeScript/">TypeScript</a></p>
                            <p class="item-title"><a href="/blog/2019/01/21/TypeScript-接口/" class="title">TypeScript 接口</a></p>
                            <p class="item-date"><time datetime="2019-01-21T08:47:26.000Z" itemprop="datePublished">2019-01-21</time></p>
                        </div>
                    </li>
                
                    <li>
                        
                        <div class="item-thumbnail">
                            <a href="/blog/2019/01/20/TypeScript-基础类型/" class="thumbnail">
    
    
        <span style="background-image:url(http://image.nicebp.com/blog/banner/TB1xJN9QXXXXXbXXpXXXXXXXXXX-900-500.jpg?imageView2/1/w/690/h/295/q/75)" alt="TypeScript 基础类型" class="thumbnail-image"></span>
    
</a>

                        </div>
                        
                        <div class="item-inner">
                            <p class="item-category"><a class="article-category-link" href="/blog/categories/TypeScript/">TypeScript</a></p>
                            <p class="item-title"><a href="/blog/2019/01/20/TypeScript-基础类型/" class="title">TypeScript 基础类型</a></p>
                            <p class="item-date"><time datetime="2019-01-20T07:01:55.000Z" itemprop="datePublished">2019-01-20</time></p>
                        </div>
                    </li>
                
                    <li>
                        
                        <div class="item-thumbnail">
                            <a href="/blog/2018/02/22/ESLint-VSCode自动化配置/" class="thumbnail">
    
    
        <span style="background-image:url(http://image.nicebp.com/blog/banner/TB1xJN9QXXXXXbXXpXXXXXXXXXX-900-500.jpg?imageView2/1/w/690/h/295/q/75)" alt="ESLint&amp;VSCode自动化配置" class="thumbnail-image"></span>
    
</a>

                        </div>
                        
                        <div class="item-inner">
                            <p class="item-category"><a class="article-category-link" href="/blog/categories/笔记/">笔记</a></p>
                            <p class="item-title"><a href="/blog/2018/02/22/ESLint-VSCode自动化配置/" class="title">ESLint&amp;VSCode自动化配置</a></p>
                            <p class="item-date"><time datetime="2018-02-22T03:47:23.000Z" itemprop="datePublished">2018-02-22</time></p>
                        </div>
                    </li>
                
            </ul>
        </div>
    </div>

    
        
    <div class="widget-wrap">
        <h3 class="widget-title">categories</h3>
        <div class="widget">
            <ul class="category-list"><li class="category-list-item"><a class="category-list-link" href="/blog/categories/TypeScript/">TypeScript</a><span class="category-list-count">4</span></li><li class="category-list-item"><a class="category-list-link" href="/blog/categories/照片/">照片</a><span class="category-list-count">1</span></li><li class="category-list-item"><a class="category-list-link" href="/blog/categories/笔记/">笔记</a><span class="category-list-count">9</span></li></ul>
        </div>
    </div>

    
        
    <div class="widget-wrap">
        <h3 class="widget-title">archives</h3>
        <div class="widget">
            <ul class="archive-list"><li class="archive-list-item"><a class="archive-list-link" href="/blog/archives/2021/01/">January 2021</a><span class="archive-list-count">1</span></li><li class="archive-list-item"><a class="archive-list-link" href="/blog/archives/2019/01/">January 2019</a><span class="archive-list-count">3</span></li><li class="archive-list-item"><a class="archive-list-link" href="/blog/archives/2018/02/">February 2018</a><span class="archive-list-count">1</span></li><li class="archive-list-item"><a class="archive-list-link" href="/blog/archives/2017/10/">October 2017</a><span class="archive-list-count">2</span></li><li class="archive-list-item"><a class="archive-list-link" href="/blog/archives/2017/09/">September 2017</a><span class="archive-list-count">1</span></li><li class="archive-list-item"><a class="archive-list-link" href="/blog/archives/2017/08/">August 2017</a><span class="archive-list-count">1</span></li><li class="archive-list-item"><a class="archive-list-link" href="/blog/archives/2017/07/">July 2017</a><span class="archive-list-count">3</span></li><li class="archive-list-item"><a class="archive-list-link" href="/blog/archives/2017/06/">June 2017</a><span class="archive-list-count">1</span></li><li class="archive-list-item"><a class="archive-list-link" href="/blog/archives/2017/04/">April 2017</a><span class="archive-list-count">1</span></li><li class="archive-list-item"><a class="archive-list-link" href="/blog/archives/2017/03/">March 2017</a><span class="archive-list-count">1</span></li><li class="archive-list-item"><a class="archive-list-link" href="/blog/archives/2017/02/">February 2017</a><span class="archive-list-count">1</span></li></ul>
        </div>
    </div>

    
        
    <div class="widget-wrap">
        <h3 class="widget-title">tags</h3>
        <div class="widget">
            <ul class="tag-list"><li class="tag-list-item"><a class="tag-list-link" href="/blog/tags/Hexo/">Hexo</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/blog/tags/TypeScript/">TypeScript</a><span class="tag-list-count">4</span></li><li class="tag-list-item"><a class="tag-list-link" href="/blog/tags/git/">git</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/blog/tags/html5-css3/">html5+css3</a><span class="tag-list-count">2</span></li><li class="tag-list-item"><a class="tag-list-link" href="/blog/tags/markdown/">markdown</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/blog/tags/照片/">照片</a><span class="tag-list-count">1</span></li></ul>
        </div>
    </div>

    
        
    <div class="widget-wrap">
        <h3 class="widget-title">tag cloud</h3>
        <div class="widget tagcloud">
            <a href="/blog/tags/Hexo/" style="font-size: 10px;">Hexo</a> <a href="/blog/tags/TypeScript/" style="font-size: 20px;">TypeScript</a> <a href="/blog/tags/git/" style="font-size: 10px;">git</a> <a href="/blog/tags/html5-css3/" style="font-size: 15px;">html5+css3</a> <a href="/blog/tags/markdown/" style="font-size: 10px;">markdown</a> <a href="/blog/tags/照片/" style="font-size: 10px;">照片</a>
        </div>
    </div>

    
        
    <div class="widget-wrap widget-list">
        <h3 class="widget-title">links</h3>
        <div class="widget">
            <ul>
                
                    <li>
                        <a href="http://fex.baidu.com/" target="_blank">Baidu FEX</a>
                    </li>
                
                    <li>
                        <a href="http://www.alloyteam.com/" target="_blank">Tencent AlloyTeam</a>
                    </li>
                
                    <li>
                        <a href="http://tgideas.qq.com/" target="_blank">Tencent TGideas</a>
                    </li>
                
                    <li>
                        <a href="https://isux.tencent.com/" target="_blank">Tencent ISUX</a>
                    </li>
                
                    <li>
                        <a href="http://eux.baidu.com/" target="_blank">Baidu EUX</a>
                    </li>
                
                    <li>
                        <a href="http://taobaofed.org/" target="_blank">Taobao FED</a>
                    </li>
                
                    <li>
                        <a href="https://75team.com/" target="_blank">Qihu 360</a>
                    </li>
                
                    <li>
                        <a href="https://jdc.jd.com/" target="_blank">JD JDC</a>
                    </li>
                
            </ul>
        </div>
    </div>


    
    <div id="toTop" class="fa fa-angle-up"></div>
</aside>

            
        </div>
        <footer id="footer">
    <div class="outer">
        <div id="footer-info" class="inner">
            &copy;2015 - 2021 Shaw<br>
            Powered by <a href="http://hexo.io/" target="_blank">Hexo</a>. Theme by <a href="http://github.com/ppoffice">PPOffice</a>
            Hosted by <a href="https://gitee.com/" target="_blank">Gitee Pages</a>
            <script src="https://s22.cnzz.com/z_stat.php?id=1271323883&web_id=1271323883" language="JavaScript"></script>
        </div>        
    </div>
</footer>
        
    
    <script src="//cdn1.lncld.net/static/js/3.0.4/av-min.js"></script>
    <script src="//cdn.jsdelivr.net/gh/xcss/valine@v1.1.6/dist/Valine.min.js"></script>
    <script>
        new Valine({
            el: '#valine-thread' ,
            notify:true,
            verify:true,
            app_id: 'Szt8HMQAazvdou8iklHizKPs-gzGzoHsz',
            app_key: 'PApmoSWTjg2awSf0Fv7VKEeR',
            placeholder: 'Just Do It'
        });
    </script>




    
        <script src="/blog/libs/lightgallery/js/lightgallery.min.js"></script>
        <script src="/blog/libs/lightgallery/js/lg-thumbnail.min.js"></script>
        <script src="/blog/libs/lightgallery/js/lg-pager.min.js"></script>
        <script src="/blog/libs/lightgallery/js/lg-autoplay.min.js"></script>
        <script src="/blog/libs/lightgallery/js/lg-fullscreen.min.js"></script>
        <script src="/blog/libs/lightgallery/js/lg-zoom.min.js"></script>
        <script src="/blog/libs/lightgallery/js/lg-hash.min.js"></script>
        <script src="/blog/libs/lightgallery/js/lg-share.min.js"></script>
        <script src="/blog/libs/lightgallery/js/lg-video.min.js"></script>
    
    
        <script src="/blog/libs/justified-gallery/jquery.justifiedGallery.min.js"></script>
    
    
        <script type="text/x-mathjax-config">
            MathJax.Hub.Config({ tex2jax: { inlineMath: [['$','$'], ['\\(','\\)']] } });
        </script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.1/MathJax.js?config=TeX-MML-AM_CHTML"></script>
    



<!-- Custom Scripts -->
<script src="/blog/js/main.js"></script>

    </div>
</body>
</html>